package com.lm.paymentadmin.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.lm.paymentadmin.domain.Organization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrganizationExcelListener extends AnalysisEventListener<Organization> {

    //不支持spring
    private JdbcTemplate jdbcTemplate;
    //通过构造器获取所需要的执行对象
    public OrganizationExcelListener(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 批处理阈值
     */
    private static final int BATCH_COUNT = 1000;
    List<Organization> list = new ArrayList<>(BATCH_COUNT);

    private static final String sql = "insert into t_organization(code,name,type,level,address,category) values(?,?,?,?,?,?)";

    @Override
    public void invoke(Organization organization, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(organization));
        list.add(organization);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData(){
        log.info("{}条数据，开始存储数据库！", list.size());
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1,list.get(i).getCode());
                ps.setString(2,list.get(i).getName());
                ps.setString(3,list.get(i).getType());
                ps.setString(4,list.get(i).getLevel());
                ps.setString(5,list.get(i).getAddress());
                ps.setString(6,list.get(i).getCategory());
            }
            @Override
            public int getBatchSize() {
                return list.size();
            }
        });
        log.info("存储数据库成功！");
    }
}
